const router = require("koa-router")();

const UUID = require("uuid");

const ChannelModel = require("../../model/Channels");
const UserChannelModel = require("../../model/UserChannels");
const UserBasic = require("../../model/UserBasic");
const UserProfile = require("../../model/UserProfile");
const { getUserIdByContext, getImage } = require("../token");
const UserRelation = require("../../model/UserRelation");
const UserRead = require("../../model/UserRead");
const ArticleBasic = require("../../model/ArticleBasic");
const { sendMessageByUserId } = require("../websocket");
const address = require('../../../address')
const multer = require("koa-multer");
const UserMessage = require('../../model/UserMessage')
const UserFeed = require('../../model/UserFeed')
//配置
let storage = multer.diskStorage({
  //文件保存路径
  destination: function (req, file, cb) {
    cb(null, "public/uploads/"); //注意路径必须存在
  },
  //修改文件名称
  filename: function (req, file, cb) {
    let fileFormat = file.originalname.split(".");
    cb(null, Date.now() + "." + fileFormat[fileFormat.length - 1]);
  },
});
//加载配置
let upload = multer({ storage });

// 获取个人的频道
router.get("/channels", async (ctx) => {
  const allChannels = await ChannelModel.find({}); // 所有频道
  const userChannels = [{ id: 0, name: "推荐" }];
  let userChannelIds = []; // 用户频道数据
  const user_id = await getUserIdByContext(ctx); // 获取用户id
  // 如果用户登录 返回用户的频道数据
  if (user_id) {
    // 如果当前用户存在 则请求用户频道表数据
    userChannelIds = await UserChannelModel.find({ user_id });
  }
  if (userChannelIds && userChannelIds.length) {
    // 如果有内容
    userChannels.push(
      ...allChannels
        .filter((item) =>
          userChannelIds.some((obj) => obj.channel_id === item.channel_id)
        )
        .map((item) => ({ id: item.channel_id, name: item.channel_name }))
    );
  } else {
    userChannels.push(
      ...allChannels
        .filter((item, index) => index < 5)
        .map((item) => ({
          id: parseInt(item.channel_id),
          name: item.channel_name,
        }))
    );
  }
  ctx.status = 200
  return { data: { channels: userChannels } };
  // 如果用户未登录 返回默认的频道数据
});
// 设置个人频道 重置式
router.put("/channels", async (ctx) => {
  const { channels } = ctx.request.body;
  const user_id = await getUserIdByContext(ctx); // 获取用户id
  if (!user_id) {
    return { success: false, message: "游客不能设置个性化频道", status: 401 };
  }
  if (!channels) {
    return {
      success: false,
      message: "用户设置的频道数据不能为空",
      status: 400,
    };
  }
  await UserChannelModel.remove({ user_id }); // 删除原来的频道
  const channelList = channels.map((item) => ({
    user_id,
    channel_id: item.id,
    sequence: item.seq,
  }));
  await UserChannelModel.insertMany(channelList);
  ctx.status = 201

  return { message: "更新用户频道成功", data: { channels } };
});
// 设置个人频道 增量式
router.patch("/channels", async (ctx) => {
  const { channels } = ctx.request.body;
  const user_id = await getUserIdByContext(ctx); // 获取用户id
  if (!user_id) {
    return { success: false, message: "游客不能设置个性化频道", status: 401 };
  }
  if (!channels) {
    return {
      success: false,
      message: "用户设置的频道数据不能为空",
      status: 400,
    };
  }
  let currentChannels = await UserChannelModel.find({ user_id }).lean() // 获取原来的频道
  if (!currentChannels.length) {
    const allChannels = await ChannelModel.find({}); // 所有频道
     currentChannels = [];
     currentChannels.push(
      ...allChannels
        .filter((item, index) => index < 5)
    );
    const defaultChannels = currentChannels.map((item) => ({
      user_id,
      channel_id: item.channel_id
    }));
    await UserChannelModel.insertMany(defaultChannels); // 先插入默认的数据
  }
  let channelList = channels.filter((item) => !currentChannels.some(obj => obj.channel_id == item.id));
   channelList = channelList.map((item) => ({
    user_id,
    channel_id: item.id,
    sequence: item.seq,
  }));
  await UserChannelModel.insertMany(channelList);
  ctx.status = 201

  return { message: "更新用户频道成功", data: { channels } };
});
// 获取用户自己的信息

// 批量删除用户的频道列表
router.delete("/channels", async (ctx) => {
  let { channels } = ctx.request.body;
  const user_id = await getUserIdByContext(ctx); // 获取用户id
  if (!user_id) {
    return { success: false, message: "游客不能设置个性化频道", status: 401 };
  }
  if (!channels) {
    return {
      success: false,
      message: "用户删除的频道数据不能为空",
      status: 400,
    };
  }
  channels = channels.map(item => item.toString())
  await UserChannelModel.deleteMany({ channel_id: { $in: channels } })
  ctx.status = 204
  return { message: "删除用户频道成功"};
});
// 批量特定的用户频道
router.delete("/channels/:target", async (ctx) => {
  let { target } = ctx.params;
  const user_id = await getUserIdByContext(ctx); // 获取用户id
  if (!user_id) {
    return { success: false, message: "游客不能设置个性化频道", status: 401 };
  }
  if (!target) {
    return { success: false, message: "要删除的频道不能为空", status: 401 };
  }
 
  await UserChannelModel.deleteOne({ channel_id: target, user_id })
  ctx.status = 204
  return { message: "删除用户频道成功"};
});
router.get("/", async (ctx) => {
  const user_id = await getUserIdByContext(ctx); // 获取用户id
  if (!user_id) {
    return {
      status: 401,
      message: "用户认证失败, 没有登录成功",
      success: false,
    };
  }
  const person = await UserBasic.findOne({ user_id }).lean();
  if (person) {
    ctx.status = 200
    const fans_count = await UserRelation.find({target_user_id: user_id }).countDocuments()
    const follow_count = await UserRelation.find({ user_id }).countDocuments()
    const art_count = await ArticleBasic.find({ user_id }).countDocuments()
    const like_count = 0

    return {
      data: {
        id: user_id,
        name: person.user_name,
        photo: getImage(person.profile_photo),
        is_media: person.is_media,
        intro: person.introduction,
        certi: person.certificate,
        art_count,
        follow_count,
        fans_count,
        like_count,
      },
    };
  } else {
    return { status: 400, message: "查无此人", success: false };
  }
});
// 获取用户资料
router.get("/profile", async (ctx) => {
  const user_id = await getUserIdByContext(ctx); // 获取用户id
  if (!user_id) {
    return { status: 401, message: "用户的身份信息缺失", success: false };
  }
  const PersonProfile = await UserProfile.findOne({ user_id }).lean();
  const PersonBasic = await UserBasic.findOne({ user_id }).lean();
  if (PersonProfile && PersonBasic) {
    ctx.status = 200
    return {
      data: {
        id: PersonProfile.user_id,
        photo: getImage(PersonBasic.profile_photo),
        name: PersonBasic.user_name,
        mobile: PersonBasic.mobile,
        gender: PersonProfile.gender,
        birthday: PersonProfile.birthday,
        intro: PersonBasic.introduction
      },
    };
  } else {
    return { data: {} };
  }
});
// 更新用户资料
router.patch("/profile", async (ctx) => {
  const { name, gender, birthday, intro } = ctx.request.body;
  const user_id = await getUserIdByContext(ctx); // 获取用户id
  if (!user_id) {
    return { status: 401, message: "用户的身份信息缺失", success: false };
  }
  const personFile = await UserProfile.findOne({ user_id }).lean();
  const personBasic = await UserBasic.findOne({ user_id }).lean();

  await UserProfile.findOneAndUpdate(
    { user_id },
    {
      birthday: birthday || personFile.birthday,
      gender: gender !== undefined ? gender : personFile.gender,
    }
  );
  await UserBasic.findOneAndUpdate(
    { user_id },
    {
      user_name: name || personBasic.user_name,
      introduction: intro || personBasic.introduction,
    }
  );
  ctx.status = 200
});
// 关注接口
router.post("/followings", async (ctx) => {
  const { target } = ctx.request.body;
  const user_id = await getUserIdByContext(ctx); // 获取用户id
  if (!target) {
    return { success: false, message: "缺少要关注的目标", status: 400 };
  }
  if (target == user_id) {
    return { success: false, message: "自己不能关注自己", status: 400 }; 
  }
  const count = await UserRelation.find({
    user_id,
    target_user_id: target,
  }).countDocuments();

  const userProfle = await UserBasic.findOne({ user_id }).lean();
  if (userProfle) {
    // 通知被关注的用户
    sendMessageByUserId(target, "following notify", {
      user_id,
      user_name: userProfle.user_name,
      user_photo: getImage(userProfle.profile_photo),
      timestamp: new Date().getTime(),
    });
    const UserInfo = await UserBasic.findOne({ user_id })
    await UserMessage.create({ type: "3", message_id: UUID.v4(), title: UserInfo.user_name, content: '关注了你', user_id })
  }
  ctx.status = 201

  if (count) {
    return { message: "OK", data: { target } };
  } else {
    await UserRelation.create({
      user_id,
      target_user_id: target,
      relation_id: UUID.v4(),
    });
    const fans_count = await UserRelation.find({  target_user_id: target  }).countDocuments() // 当前关注人的粉丝
    await UserBasic.findOneAndUpdate({ user_id: target }, { fans_count }) // 更新实际数量
    return { message: "OK", data: { target } };
  }
});
// 取消关注接口
router.delete("/followings/:id", async (ctx) => {
  const { id } = ctx.params;
  const user_id = await getUserIdByContext(ctx); // 获取用户id
  if (!id) {
    return { success: false, message: "缺少要取消关注的目标", status: 400 };
  }
  await UserRelation.findOneAndRemove({ user_id, target_user_id: id });
  const fans_count = await UserRelation.find({  target_user_id: id  }).countDocuments() // 当前关注人的粉丝
  await UserBasic.findOneAndUpdate({ user_id: id }, { fans_count }) // 更新实际数量
  ctx.status = 204 // 取消关注的状态码
});
// 获取用户关注的列表
router.get("/followings", async (ctx) => {
  const user_id = await getUserIdByContext(ctx); // 获取用户id
  if (!user_id) {
    return { success: false, message: "用户信息缺失", status: 400 };
  }
  let { page = 1, per_page = 10 } = ctx.request.query;
  page = parseInt(page);
  per_page = parseInt(per_page);
  if (!user_id) {
    return { success: false, message: "用户未认证", status: 401 };
  }
  const total_count = await UserRelation.find({ user_id }).countDocuments();
  let results = await UserRelation.aggregate([
    {
      $lookup: {
        from: "user_basic",
        localField: "target_user_id",
        foreignField: "user_id",
        as: "userInfo",
      },
    },
    {
      $match: {
        user_id,
      },
    },
    {
      $skip: (page - 1) * per_page,
    },
    {
      $limit: per_page,
    },
  ]);
 const relations = await UserRelation.find()
  results = results.map((item) => ({
    id: item.user_id,
    name:
      item.userInfo && item.userInfo.length ? item.userInfo[0].user_name : "",
    photo:
      item.userInfo && item.userInfo.length
        ? getImage(item.userInfo[0].profile_photo)
        : "",
    fans_count:
    item.userInfo && item.userInfo.length && item.userInfo[0].fans_count ? item.userInfo[0].fans_count : 0, // 粉丝数
    mutual_follow: relations.some(obj => obj.user_id === user_id && obj.target_user_id === item.user_id) 
     && relations.some(obj => obj.target_user_id === user_id && obj.user_id === item.user_id)
    , // 暂时这么写
    //  mutual_follow: item.target_user_id === user_id,  // 是否互相关注
  }));
  ctx.status = 200
  return { data: { page, per_page, results, total_count } };
});

// 获取粉丝列表
router.get("/followers", async (ctx) => {
  const user_id = await getUserIdByContext(ctx); // 获取用户id
  if (!user_id) {
    return { success: false, message: "用户信息缺失", status: 400 };
  }
  let { page = 1, per_page = 10 } = ctx.request.query;
  page = parseInt(page);
  per_page = parseInt(per_page);
  if (!user_id) {
    return { success: false, message: "用户未认证", status: 401 };
  }
  const total_count = await UserRelation.find({ user_id }).countDocuments();
  let results = await UserRelation.aggregate([
    {
      $lookup: {
        from: "user_basic",
        localField: "user_id",
        foreignField: "user_id",
        as: "userInfo",
      },
    },
    {
      $match: {
        target_user_id: user_id,
      },
    },
    {
      $skip: (page - 1) * per_page,
    },
    {
      $limit: per_page,
    },
  ]);
  const relations = await UserRelation.find()

  results = results.map((item) => ({
    id: item.user_id,
    name:
      item.userInfo && item.userInfo.length ? item.userInfo[0].user_name : "",
    photo:
      item.userInfo && item.userInfo.length
        ? getImage(item.userInfo[0].profile_photo)
        : "",
    fans_count:
      item.userInfo && item.userInfo.length && item.userInfo[0].fans_count ? item.userInfo[0].fans_count : 0, // 粉丝数
      mutual_follow: relations.some(obj => obj.user_id === user_id && obj.target_user_id === item.user_id) 
      && relations.some(obj => obj.target_user_id === user_id && obj.user_id === item.user_id)    //  mutual_follow: item.target_user_id === user_id,
  }));
  ctx.status = 200

  return { data: { page, per_page, results, total_count } };
});
// 编辑用户头像
router.patch(
  "/photo",
  upload.fields([{ name: "photo", maxCount: 1 }]),
  async (ctx) => {
    const { photo } = ctx.req.files;
    let filePath = "";
    if (photo && photo.length) {
      filePath = `http://${address.host}:${address.port}/uploads/` + photo[0].filename;
      const user_id = await getUserIdByContext(ctx); // 获取用户id
      if (!user_id) {
        return { success: false, message: "用户信息缺失", status: 401 };
      }
      await UserBasic.findOneAndUpdate(
        { user_id },
        { profile_photo: filePath }
      );
    }
    ctx.status = 200

    return { data: { photo: filePath } };
  }
);
// 获取用户历史
router.get("/histories", async (ctx) => {
  const user_id = await getUserIdByContext(ctx); // 获取用户id
  if (!user_id) {
    return { success: false, message: "用户信息缺失", status: 401 };
  }
  let { page = 1, per_page = 10 } = ctx.request.query;
  page = parseInt(page);
  per_page = parseInt(per_page);
  if (!user_id) {
    return { success: false, message: "用户未认证", status: 401 };
  }
  const total_count = await UserRead.find({ user_id }).countDocuments();
  let results = await UserRead.aggregate([
    {
      $lookup: {
        from: "news_article_basic",
        localField: "article_id",
        foreignField: "article_id",
        as: "articleInfo",
      },
    },
    {
      $lookup: {
        from: "user_basic",
        localField: "user_id",
        foreignField: "user_id",
        as: "user",
      },
    },
    {
      $match: {
        user_id,
      },
    },
    {
      $skip: (page - 1) * per_page,
    },
    {
      $limit: per_page,
    },
  ]);
  results = results.map((item) => ({
    art_id: item.article_id,
    title:
      item.articleInfo && item.articleInfo.length
        ? item.articleInfo[0].title
        : "",
    aut_id: item.user_id,
    comm_count:
      item.articleInfo && item.articleInfo.length
        ? item.articleInfo[0].comment_count
        : 0,
    pubdate:
      item.articleInfo && item.articleInfo.length
        ? item.articleInfo[0].create_time
        : "",
    aut_name: item.user && item.user.length ? item.user[0].user_name : "无名氏",
    is_top: 0,
    cover: item.cover && item.cover.split(',').length ? { type: item.cover.split(',').length, images: item.cover.split(',')  } :{ type: 0 }
  }));
  ctx.status = 200

  return { data: { page, per_page, results, total_count } };
});

// 获取用户文章列表
router.get("/articles", async (ctx) => {
  const user_id = await getUserIdByContext(ctx); // 获取用户id
  if (!user_id) {
    return { success: false, message: "用户信息缺失", status: 401 };
  }
  let { page = 1, per_page = 10 } = ctx.request.query;
  page = parseInt(page);
  per_page = parseInt(per_page);
  if (!user_id) {
    return { success: false, message: "用户未认证", status: 401 };
  }
  const total_count = await ArticleBasic.find({ user_id }).countDocuments();
  let results = await ArticleBasic.aggregate([
    {
      $lookup: {
        from: "user_basic",
        localField: "user_id",
        foreignField: "user_id",
        as: "user",
      },
    },
    {
      $lookup: {
        from: "news_attitude",
        localField: "article_id",
        foreignField: "article_id",
        as: "attitudeInfo",
      },
    },
    {
      $match: {
        user_id,
      },
    },
    {
      $skip: (page - 1) * per_page,
    },
    {
      $limit: per_page,
    },
  ]);
  results = results.map((item) => ({
    art_id: item.article_id,
    title: item.title,
    aut_id: item.user_id,
    pubdate: item.create_time,
    aut_name: item.user && item.user.length ? item.user[0].user_name : "无名氏",
    is_top: 0,
    cover: item.cover && item.cover.split(',').length ? { type: item.cover.split(',').length, images: item.cover.split(',')  } :{ type: 0 },
    like_count: item.attitudeInfo.filter((item) => item.attitude == 1).length, // 点赞数
    comm_count: item.comment_count,
  }));
  ctx.status = 200

  return { data: { page, per_page, results, total_count } };
});
router.get('/figure',  async (ctx) => {
  const user_id = await getUserIdByContext(ctx); // 获取用户id
  if (!user_id) {
    return { success: false, message: "用户信息缺失", status: 401 };
  }
  const userInfo = await UserBasic.findOne({ user_id }).lean()
  const MyArticle = await ArticleBasic.find({ user_id }).lean()
  let read_count = 0
  MyArticle.forEach(item => {
    read_count = read_count + (isNaN(parseInt(item.read_count)) ?  0 : parseInt(item.read_count))
  })
  ctx.status = 200
  return  { data: { read_count, fans_count: userInfo.fans_count || 0  } }
})


// 获取消息列表
router.get("/notify", async (ctx) => {
  const user_id = await getUserIdByContext(ctx); // 获取用户id
  const { type } = ctx.query
  if (!user_id) {
    return { success: false, message: "用户信息缺失", status: 401 };
  }
  let { page = 1, per_page = 10 } = ctx.request.query;
  page = parseInt(page);
  per_page = parseInt(per_page);
  if (!user_id) {
    return { success: false, message: "用户未认证", status: 401 };
  }
  let match = { user_id }
  if (type) {
    match = { user_id, type }
  }
  const total_count = await UserMessage.find(match).countDocuments();
  let results = await UserMessage.aggregate([
    {
      $match: match
    },
    {
      $skip: (page - 1) * per_page,
    },
    {
      $limit: per_page,
    },
  ]);

  results = results.map((item) => ({
    id: item.message_id,
    title: item.title,
    content: item.content,
    comment_target: item.comment_target,
    comment_content: item.comment_content,
    create_time: item.create_time
  }));
  ctx.status = 200

  return { data: { page, per_page, results, total_count } };
});
// 提交反馈
router.post("/feedback", async (ctx) => {
  const user_id = await getUserIdByContext(ctx); // 获取用户id
  const { mobile, images, intro } = ctx.request.body;
  if (!user_id) {
    return { success: false, message: "用户信息缺失", status: 401 };
  }
  if (!mobile || !intro) {
    return { success: false, message: "手机号和反馈不能为空", status: 400 };
  }

  const data = await UserFeed.create({ user_id, mobile, images, intro  })
  ctx.status = 200
  return { data }
});
module.exports = router.routes();
